package com.wosai.teach.utils;

import java.io.File;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.widget.Toast;

import com.android.agnetty.constant.CharsetCst;
import com.android.agnetty.utils.BaseUtil;
import com.android.agnetty.utils.StringUtil;
import com.wosai.teach.activity.LoginActivity;
import com.wosai.teach.activity.SplashActivity;
import com.wosai.teach.dao.InstallDao;
import com.wosai.teach.pojo.Install;

public class AppUtil {
	private static final String PARAMETERS_SEPARATOR = "&";
	private static final String EQUAL_SIGN = "=";
	private static final int BLACK = 0xff000000;
	private static final int WHITE = 0xffffffff;

	/**
	 * 获取当前时间，格式为yyyy-MM-dd hh:mm:ss
	 * 
	 * @return
	 */
	public static String getTime() {
		Date today = new Date();
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.getDefault());
		return f.format(today);
	}

	/**
	 * 获取校验码
	 * 
	 * @param str
	 * @return
	 */
	public static String getToken(LinkedHashMap<String, String> paramsMap) {
		StringBuilder paras = new StringBuilder("token[");
		if (paramsMap != null && paramsMap.size() > 0) {
			Iterator<Map.Entry<String, String>> ite = paramsMap.entrySet()
					.iterator();
			try {
				while (ite.hasNext()) {
					Map.Entry<String, String> entry = (Map.Entry<String, String>) ite
							.next();
					paras.append(entry.getKey()).append(EQUAL_SIGN)
							.append(StringUtil.nullToEmpty(entry.getValue()));
					if (ite.hasNext()) {
						paras.append(PARAMETERS_SEPARATOR);
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		paras.append("]");
		// LogUtil.i("TOKEN: "+paras.toString());
		String token = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			token = BaseUtil.bytesToHexString(md.digest(paras.toString()
					.getBytes(CharsetCst.UTF_8)));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return token;
	}

	/**
	 * 获取当前运行界面的包名
	 * 
	 * @param context
	 * @return
	 */
	public static String getTopPackageName(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
		return cn.getPackageName();
	}

	/**
	 * 获取栈顶activity
	 * 
	 * @param context
	 * @return
	 */
	public static ComponentName getTopActivity(Activity context) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Activity.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
		if (runningTaskInfos != null)
			return runningTaskInfos.get(0).topActivity;
		else
			return null;
	}

	/**
	 * 显示Toast
	 * 
	 * @param context
	 * @param resId
	 */
	public static void showToast(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 显示Toast
	 * 
	 * @param context
	 * @param text
	 */
	public static void showToast(Context context, String text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 安装
	 * 
	 * @param activity
	 */
	public static void install(Activity activity, int expId) {
		InstallDao instDao = new InstallDao();
		Install inst = instDao.getInstallByExpId(expId);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(inst.getSavePath())),
				"application/vnd.android.package-archive");
		activity.startActivityForResult(intent, inst.getRequestCode());
	}

	public static void install(Fragment fragment, int expId) {
		AppGlobal.curInstExpId = expId;
		InstallDao instDao = new InstallDao();
		Install inst = instDao.getInstallByExpId(expId);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(inst.getSavePath())),
				"application/vnd.android.package-archive");
		fragment.startActivityForResult(intent, inst.getRequestCode());
	}

	/**
	 * 提示跳转到登录页面
	 * 
	 * @param curAct
	 * @return
	 */
	public static boolean toLogin(final Activity curAct) {
		if (AppGlobal.user == null) {
			new AlertDialog.Builder(curAct)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setMessage("需要登录才能操作，是否登录")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent it = new Intent(curAct,
											LoginActivity.class);
									curAct.startActivity(it);
									curAct.finish();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 点击“返回”后的操作,这里不设置没有任何操作
								}
							}).show();
			return true;
		} else {
			return false;
		}
	}

	private static long exitTime = 0;

	public static void AppOut(int keyCode, KeyEvent event, Activity activity) {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(activity, "再按一次退出软件", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
//			Intent intent = new Intent(activity, SplashActivity.class);
			Intent intent = new Intent();
			intent=activity.getIntent();
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			intent.putExtra("finish", true);
//			activity.startActivity(intent);
			activity.finish();
		}
	}

}
